package com.pangolin.pangolinim.ui.activity;

import android.content.Intent;
import android.net.Uri;

import com.lqr.optionitemview.OptionItemView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.language.LanguageConfig;
import com.orhanobut.logger.Logger;
import com.pangolin.pangolinim.R;
import com.pangolin.pangolinim.app.BroadcastMsg;
import com.pangolin.pangolinim.net.NetFormat;
import com.pangolin.pangolinim.ui.adapter.UIContact;
import com.pangolin.pangolinim.ui.base.BaseActivity;
import com.pangolin.pangolinim.utils.BundleUtil;
import com.pangolin.pangolinim.utils.FileUtil;
import com.pangolin.pangolinim.utils.GlideEngine;
import com.pangolin.pangolinim.utils.GsonUtil;
import com.pangolin.pangolinim.utils.UIUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccAndSafeActivity extends BaseActivity {
    private UIContact me;

    private OptionItemView mOivChangeName;
    private OptionItemView mOivChangePasswd;
    private OptionItemView mOivChangeHeader;
    private OptionItemView mOivClearAll;

    @Override
    protected void init(){
        String strMe = getIntent().getStringExtra("param1");
        if(strMe != null){
            me = GsonUtil.fromJson(strMe , UIContact.class);
        }
    }

    @Override
    protected void initView(){
        mOivChangeName = findViewById(R.id.oivChangeName);
        mOivChangePasswd = findViewById(R.id.oivChangePasswd);
        mOivClearAll = findViewById(R.id.oivClearAll);
        mOivChangeHeader = findViewById(R.id.oivChangeHeader);

        setToolbarTitle(UIUtil.getString(R.string.acc_and_safe));
    }

    @Override
    protected void initListener(){
        mOivChangeName.setOnClickListener(v -> {
            jumpToActivity(ChangeNameActivity.class , GsonUtil.toJson(me));
        });
        mOivChangePasswd.setOnClickListener(v -> {
            jumpToActivity(ChangePassActivity.class , GsonUtil.toJson(me));
        });
        mOivClearAll.setOnClickListener(v -> {
            showMaterialDialog(UIUtil.getString(R.string.clear_all),
                    UIUtil.getString(R.string.clear_all_content),
                    UIUtil.getString(R.string.clear),
                    UIUtil.getString(R.string.cancel),
                    v1 -> {
                        hideMaterialDialog();
                        clearAllData();
                    },
                    v2 -> hideMaterialDialog());
        });
        mOivChangeHeader.setOnClickListener(v -> {
            //获取用户选择的图片路径
            picPicker();
        });
    }

    @Override
    protected void CoreMessage(BundleUtil bundleUtil){
        if(bundleUtil.getType() == BroadcastMsg.SIG_CORE_DATA){
            if(bundleUtil.getData() != null){
                Map<String, Object> resMap = bundleUtil.getData();
                if((int) resMap.get("type") == BroadcastMsg.DATA_CORE_REINFO){
                    if((int)resMap.get("result") == 0){
                        UIUtil.showToast("修改成功");
                    }else{
                        UIUtil.showToast(NetFormat.ResMsg((int) resMap.get("result")));
                    }
                }
            }
        }
    }

    @Override
    protected int provideContentViewId(){
        return R.layout.activity_acc_and_safe;
    }

    //清空所有数据并退出
    private void clearAllData(){

    }

    /**
     TODO：调用系统图片选择器
     */
    private void picPicker(){
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_WeChat_style)
                .isWeChatStyle(true)
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE )// 多选 or 单选
                .isCamera(false)// 是否显示拍照按钮
                .isGif(false)// 是否显示gif图片
                .setLanguage(LanguageConfig.CHINESE)    //中文版
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> results = PictureSelector.obtainMultipleResult(data);
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    if(results.size() > 0){
                        try {
                            //拷贝到程序私有目录
                            String newFile = FileUtil.copyGalleryToPrivate(
                                    UIUtil.getContext() ,
                                    Uri.parse(results.get(0).getPath()) ,
                                    String.valueOf(me.getUid()),
                                    120 ,
                                    120);
                            Logger.d("onActivityResult:filename:"+newFile);
                            //上传文件并发送消息
                            uploadFileToServer(newFile);
                            //发送修改用户信息请求
                            Map<String, Object> brocastMap = new HashMap<String, Object>();
                            brocastMap.put("type" , BroadcastMsg.DATA_UI_REINFO);
                            brocastMap.put("username" , me.getName());
                            brocastMap.put("headimg" , newFile);
                            BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
                            BroadcastSender(bundleUtil.getBundle());
                        }catch (Exception e){
                            UIUtil.showToast(e.getMessage());
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * TODO:上传文件请求
     * @param filename 存放在用户目录uid文件夹下的文件的文件名
     */
    private void uploadFileToServer(String filename){
        Map<String, Object> brocastMap = new HashMap<String, Object>();
        brocastMap.put("type" , BroadcastMsg.DATA_UI_UPLOADPIC);
        brocastMap.put("filename" , filename);
        BundleUtil bundleUtil = new BundleUtil(BroadcastMsg.SIG_UI_DATA , brocastMap , null);
        BroadcastSender(bundleUtil.getBundle());
    }
}